package com.probox.common.entity.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Kite
 * @date 2021/7/10
 */
public class HttpUtil {

    public static String PostUrl(String requesturl, JSONObject pm_str) {
        String res = null;
        //1.建立连接
        try {
            URL url = new URL(requesturl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  //打开链接
            //1.1输入输出设置
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Charset", "UTF-8");
            byte[] data = (pm_str.toString()).getBytes();
            // httpUrlConn.setRequestProperty("Content-Length", String.valueOf(data.length));
            httpUrlConn.setRequestProperty("content-type", "application/json");
            httpUrlConn.setRequestProperty("accept", "application/json");

            httpUrlConn.connect();

            OutputStream out = httpUrlConn.getOutputStream();
            String jsonStirng = pm_str.toString();
            // 写入请求的字符串
            out.write(jsonStirng.getBytes());
            out.flush();
            out.close();

            if (httpUrlConn.getResponseCode() == 200) {

                InputStream in = httpUrlConn.getInputStream();
                byte[] data1 = new byte[in.available()];
                in.read(data1);
                // 转成字符串
                res = new String(data1);
                return res;

            } else {
                return res;
            }
        } catch (Exception e1) {

            e1.printStackTrace();
            return res;
        }

    }
}
